;(function() {

"use strict";

/**
 * @type {Object.<string, number>}
 * @const
 */
var KeyCodeTable = {
	H : 72, J : 74, K : 75, O : 79, V : 86
};

var HotKey = {


	init : function() {
		'use strict';
		HotKey.currentFloor = -1;

		var pos = $( '.l_post' );
		if ( pos.length ) {

			$( document ).keydown( keyListener );

			pos.forEach( function( post, i ) {
				post.order = i;
				if ( post.getElementsByTagName( 'b' ).length ) {
					post.lit();
					HotKey.currentFloor = i;
				}
			});

			pos.click( function( e ) {
				if ( e.button === 0 && e.target.tagName !== 'A' ) {
					pos[HotKey.currentFloor] && pos[HotKey.currentFloor].semiLit();
					this.lit();
					HotKey.currentFloor = this.order;
				}
			} );

			pos[0].semiLit();
		}
	}


};


function keyListener( e ) {
	"use strict";

	if ( document.activeElement !== document.body || e.ctrlKey )
		return;

	switch ( e.keyCode ) {

		// JKscroll
		case KeyCodeTable.J :
			var mainFloor = $( '.l_post' )[HotKey.currentFloor + 1];
			if ( mainFloor ) {
				mainFloor.focusIntoView();
				if ( mainFloor.pre() )
					mainFloor.pre().semiLit();
				HotKey.currentFloor++;
			} else {
				return;
			}
			break;

		case KeyCodeTable.K :
			var mainFloor = $( '.l_post' )[HotKey.currentFloor - 1];
			if ( mainFloor ) {
				mainFloor.focusIntoView();
				if ( mainFloor.next() )
					mainFloor.next().semiLit();
				HotKey.currentFloor--;
			} else {
				return;
			}
			break;

		case KeyCodeTable.O :
			if ( HotKey.currentFloor === -1 )
				return;
			var mainFloor = $( '.l_post' )[HotKey.currentFloor];
			mainFloor.toggle();
			if ( $( mainFloor ).hasClass( 'bdb-collapse' ) && mainFloor.next() ) {
				mainFloor.next().focusIntoView();
				HotKey.currentFloor++;
			}
			break;

		case KeyCodeTable.V :
			if (HotKey.currentFloor === -1)
				return;
			var mainFloor = $( '.l_post' )[HotKey.currentFloor];
			var _author = mainFloor.getAuthor();
			if ( _author )
				open( 'http://www.baidu.com/p/' + encodeURIComponent( _author ) );
			break;

		case KeyCodeTable.H :
			$( '#tb_header_search_form' )[0].submit();
			break;
	}

}

window.HotKey = HotKey;

})();
